from dataclasses import dataclass, field

from fastapi import APIRouter
from pydantic import BaseModel

router = APIRouter()

@dataclass
class Item():
    name: str
    price: float
    description: str | None =  None
    tax: float | None = None

@router.post("/items")
async def create_item(item: Item):
    return item


items = {
    "华为手机": {"name": "华为手机", "price": 3999.0},
    "小米手机": {"name": "小米手机", "description": "红米手机","price": 2999.0},
    "苹果手机": {"name": "苹果手机", "description": None, "price": 4999.0,"tax": 10.5}
}

# 使用response_model_exclude_unset与Pydantic有点不一样，这里定义时有默认值也会展示出来，不管你有没有明确的给赋值
@router.get("/items/{item_name}",response_model=list[Item],response_model_exclude_unset=True)
async def read_item(item_name: str):
    result = [item for name, item in items.items() if item_name in name]
    return result

@dataclass
class Book:
    name: str
    description: str | None = None

@dataclass
class Author:
    name: str
    # python的dataclass中，使用可变对象（list,dict）作为默认值会导致所有实例共享同一对象，这是不安全的
    # 这里应使用field(default_factory=list)
    # 下面这种写法Pydantic中BaseModel写是可以的
    # books: list[Book] = []
    books: list[Book] = field(default_factory=list)

@router.post("/authors/{author_name}/books", response_model=Author)
async def create_author_books(author_name: str, books: list[Book]):
    return {
        "name": author_name,
        "books": books
    }